﻿using System;
using Microsoft.Xna.Framework.Graphics;

namespace XNAGuiLib.Core.Utilities
{
    public class TextWrapper
    {

        #region TextWrapper Public Static Method - WrapToFitWidth(string text, SpriteFont font, int width)
        public static string WrapToFitWidth(string text, SpriteFont font, int width)
        {
            string retVal = text;

            if (text.Contains(" "))
            {
                retVal = "";
                string[] splittedText = text.Split(new string[] { " " }, StringSplitOptions.None);
                string tempLine = "";

                foreach (string part in splittedText)
                {
                    if (font.MeasureString(tempLine + part + " ").X + (int)(font.Spacing * 0.75) < width)
                    {
                        tempLine += part + " ";
                    }
                    else
                    {
                        retVal += tempLine + "\n";
                        tempLine = part + " ";
                    }
                }

                retVal += tempLine;
            }
            return retVal;
        }
        #endregion

        #region TextWrapper Public Static Method - CapToFitHeight(string text, SpriteFont font, int height)
        public static string CapToFitHeight(string text, SpriteFont font, int height)
        {
            string retVal = "";

            string tempText = text;
            if (tempText.Contains("\\n"))
            {
                while (font.MeasureString(tempText.Substring(0, tempText.LastIndexOf("\n"))).Y + font.LineSpacing * 0.75 > height)
                {
                    tempText = tempText.Substring(0, tempText.LastIndexOf("\n"));
                }
                if (tempText.Length < text.Length)
                    retVal = tempText.Substring(0, tempText.Length - 3) + "...";
                else retVal = tempText;
            }
            else retVal = tempText;

            return retVal;
        }
        #endregion

        #region TextWrapper Public Static Method - WrapToFit(string text, SpriteFont font, int width, int height)
        public static string WrapToFit(string text, SpriteFont font, int width, int height)
        {
            return TextWrapper.CapToFitHeight(TextWrapper.WrapToFitWidth(text, font, width), font, height);
        }
        #endregion
    }
}
